<template>
  <div class="campusCircleWrap">
    <van-nav-bar
      title="详情"
      left-text="返回"
      left-arrow
      fixed
      @click-left="onClickLeft"
    ></van-nav-bar>
    <div class="content">
      <div class="postWrap">
        <van-popover
          v-model="showPopover"
          trigger="click"
          :actions="actions"
          placement="bottom-end"
          @select="onSelect"
          class="popover_more"
        >
          <template #reference>
            <van-icon name="ellipsis" />
          </template>
        </van-popover>
        <div class="postHeader">
          <div class="postHeader_img" @click="toUserDetail">
            <img
              v-if="postList.user && postList.user[0].headPic"
              :src="postList.user[0].headPic.content"
              alt=""
              ref="headPic"
              :style="headPicHeight"
            />
            <img
              v-else
              src="static/images/headPic.png"
              alt=""
              ref="headPic"
              :style="headPicHeight"
            />
          </div>
          <div>
            <span
              class="postHeader_name"
              v-if="postList.user"
              @click="toUserDetail"
              >{{ postList.user[0].username }}</span
            >
            <span class="postHeader_time" v-if="postList.createTime">{{
              postList.createTime
            }}</span>
          </div>
        </div>
        <div class="postWord">
          <span class="postWord_span">{{ postList.title }}</span>
          <van-tag type="primary">{{postList.modulename}}</van-tag>
          <p class="huanhang">
            {{ postList.content }}
          </p>
        </div>
        <div class="postImg">
          <img
            :src="pic.content"
            alt=""
            v-for="(pic, index) in postList.pictures"
            :key="index"
            @click="openImg(pic.content)"
          />
        </div>
        <div class="postFooter">
          <div class="read">
            <van-icon class="van-icon" name="browsing-history-o" />
            <span>{{ postList.readNum }}</span>
          </div>
          <div class="comment">
            <van-icon name="comment-o" />
            <span v-if="postList.commentList">{{
              postList.commentList.length
            }}</span>
          </div>
          <div v-if="user" class="star" @click.stop="starChange(postList)">
            <van-icon
              v-if="user[0].star && user[0].star.indexOf(postList._id) === -1"
              name="star-o"
            />
            <van-icon v-else name="star" />
          </div>
          <div v-if="postList" class="like" @click.stop="lickChange(postList)">
            <van-icon
              v-if="
                postList.likeList &&
                postList.likeList.indexOf(user[0]._id) === -1
              "
              name="like-o"
            />
            <van-icon v-else name="like" />
            <span v-if="postList.likeList">{{ postList.likeList.length }}</span>
          </div>
        </div>
      </div>
      <div class="commentWrap">
        <div class="commentTop">
          <div class="comment_comtent">评论</div>
          <div class="comment_publish" @click="commentPublish">发布评论</div>
        </div>
        <van-divider />
        <div v-if="postList.commentList && postList.commentList.length > 0">
          <div
            v-for="(item, index) in postList.commentList"
            :key="index"
            class="commentListWrap"
          >
            <div
              class="comment_good"
              @click.stop="lick_commentChange(item, index)"
            >
              <van-icon
                name="good-job-o"
                v-if="
                  item.likeList && item.likeList.indexOf(user[0]._id) === -1
                "
              />
              <van-icon name="good-job" v-else />
              <span>{{ item.likeList.length }}</span>
            </div>
            <div class="postHeader">
              <div class="postHeader_img" @click="toUserDetail1(item)">
                <img
                  v-if="item.user[0].headPic"
                  :src="item.user[0].headPic.content"
                  alt=""
                  ref="headPic"
                  :style="headPicHeight"
                />
                <img
                  v-else
                  src="static/images/headPic.png"
                  alt=""
                  ref="headPic"
                  :style="headPicHeight"
                />
              </div>
              <div>
                <span
                  class="postHeader_name"
                  v-if="item.user"
                  @click="toUserDetail1(item)"
                  >{{ item.user[0].username }}</span
                >
                <span class="postHeader_time" v-if="item.createTime">{{
                  item.createTime
                }}</span>
              </div>
            </div>
            <div class="postWord">
              <p class="huanhang" v-if="item.content">
                {{ item.content }}
              </p>
              <p class="huanhang" v-else>
                [该评论已被删除]
              </p>
            </div>
            <div class="floor">
              <span style="color:red" @click="deleteComment(item,index)" v-if="item.user&&user&&item.user[0]._id===user[0]._id&&item.content">删除</span>
              <span>第{{ postList.commentList.length - index }}楼</span>
            </div>
            <van-divider />
          </div>
        </div>
        <van-empty v-else description="还未有评论，快去发布第一个评论吧！" />
      </div>
    </div>
    <!-- 点击图片放大 显示遮罩层 -->
    <van-overlay :show="overlayShow" @click="overlayShow = false">
      <div class="overlay">
        <img :src="overlaySrc" alt="" class="overlayimg" />
      </div>
    </van-overlay>
    <!-- 点击发布评论 显示遮罩层 -->
    <van-overlay :show="overlayCommentShow">
      <div class="overlay">
        <div class="sendMessage_Wrap">
          <div class="sendMessage">
            <van-field
              v-model="commentList.content"
              type="textarea"
              :auto-focus="true"
              placeholder="请输入评论"
              :autosize="commentHeight"
              class="sendMessage_input"
            />
            <van-button
              type="primary"
              class="sendMessage_button1"
              @click="sendMessage"
              >发送</van-button
            >
            <van-button
              class="sendMessage_button2"
              @click="overlayCommentShow = false"
              >取消</van-button
            >
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import {
  getPostDetail,
  setReadNum,
  setStar,
  createCommentList,
  setLikeList,
  setCommentLikeList,
  removePost,
  setReportList,
  deletePostcomment
} from '@/views/api/api.js'
import { Toast, Dialog } from 'vant'
export default {
  components: {},
  data () {
    return {
      activeKey: 0,
      oldCommentList: [],
      isShowPopup: false,
      modulename: '',
      applyReason: '',
      user: '',
      // sidebarList: [],
      postList: [],
      overlayShow: false, // z遮罩层
      overlayCommentShow: false, // 发布评论遮罩层
      overlaySrc: '', // 遮罩层上图片的地址
      headPicHeight: '',
      postID: '', // 路径的帖子id
      message: '', // 评论
      commentList: {
        content: '',
        createTime: '',
        user: [],
        likeList: []
      }, // 评论列表
      commentHeight: { maxHeight: 100, minHeight: 50 }, // 输入评论框的高度
      isStarAdd: false, // 是否收藏
      isAdd: false, // 是否点赞  不是取消赞
      isAdd_comment: false,
      // slidebarUser: []
      showPopover: false,
      showPopover_comment: false,
      // 通过 actions 属性来定义菜单选项
      actions: [
        {
          text: '删除',
          disabled: false
        },
        { text: '举报', disabled: false },
        { text: '取消举报', disabled: false }
      ],
      commentListTime: [],
      value2: '1',
      option2: [
        { text: '时间排序', value: '1' },
        { text: '点赞排序', value: '2' }
      ]
    }
  },
  computed: {},
  created () {
    // console.log(window.WebSocket, 1111)
    this.init()
  },
  mounted () {},
  methods: {
    init () {
      // 获取用户信息
      this.user = JSON.parse(sessionStorage.getItem('user'))
      // 获取路径上的postID
      this.postID = this.$route.query.postID
      // 初始化，从数据库中获取的帖子信息 根据路径传过来的帖子id
      let params = {
        id: this.postID
      }
      getPostDetail(params).then((res) => {
        if (res.data.code) {
          Toast.fail(res.data.msg)
        } else {
          // 查询成功
          this.commentListTime = JSON.parse(
            JSON.stringify(res.data.Info[0].commentList)
          )
          this.postList = res.data.Info[0]
          this.postList.commentList = this.postList.commentList.reverse()
          // UTC时间标准时间格式转通用时间格式
          this.postList.createTime = this.utc2beijing(this.postList.createTime)
          this.oldCommentList = JSON.parse(
            JSON.stringify(this.postList.commentList)
          )
          for (let i = 0; i < this.postList.commentList.length; i++) {
            this.postList.commentList[i].createTime = this.utc2beijing(
              this.postList.commentList[i].createTime
            )
          }
          this.postList.readNum++
          let param = {
            id: this.postID,
            readNum: this.postList.readNum
          }
          // 判断帖子发布人是否是当前用户，是则可以删除功能
          this.actions[0].disabled =
            this.user[0]._id !== this.postList.user[0]._id
          this.actions[1].disabled = (this.postList.reportList.indexOf(this.user[0]._id) !== -1)
          this.actions[2].disabled = (this.postList.reportList.indexOf(this.user[0]._id) === -1)
          setReadNum(param).then((res) => {
            if (res.data.code) {
              // Toast.fail(res.data.msg)
            } else {
              // 阅读成功
            }
          })
        }
      })
    },
    getPostDetail () {
      let params = {
        id: this.postID
      }
      getPostDetail(params).then((res) => {
        if (res.data.code) {
          Toast.fail(res.data.msg)
        } else {
          // 查询成功
          this.commentListTime = JSON.parse(
            JSON.stringify(res.data.Info[0].commentList)
          )
          this.postList = res.data.Info[0]
          this.postList.commentList = this.postList.commentList.reverse()
          // UTC时间标准时间格式转通用时间格式
          this.postList.createTime = this.utc2beijing(this.postList.createTime)
          this.oldCommentList = JSON.parse(JSON.stringify(this.postList.commentList))
          for (let i = 0; i < this.postList.commentList.length; i++) {
            this.postList.commentList[i].createTime = this.utc2beijing(
              this.postList.commentList[i].createTime
            )
          }
          // this.postList.commentList = this.postList.commentList.reverse()
        }
      })
    },
    lickChange (item) {
      // 判断当前用户是否点赞过，即是否在likeList中 在则从likeList删除，不在则push进去
      if (item.likeList.indexOf(this.user[0]._id) === -1) {
        this.isAdd = true
      } else {
        this.isAdd = false
      }
      // 将likeList写入数据库
      let params = {
        isAdd: this.isAdd,
        userID: this.user[0]._id,
        id: item._id
      }
      setLikeList(params).then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          item.likeList = res.data.Info[0].likeList
        }
      })
    },
    starChange (item) {
      // 判断当前用户是否收藏过，即是否在likeList中 在则从likeList删除，不在则push进去
      if (this.user[0].star.indexOf(item._id) === -1) {
        this.isStarAdd = true
        this.user[0].star.push(item._id)
        console.log(this.user[0].star)
      } else {
        this.isStarAdd = false
        this.user[0].star.splice(item._id, 1)
        console.log(this.user[0].star)
      }
      // 将likeList写入数据库
      let params = {
        isAdd: this.isStarAdd,
        userID: this.user[0]._id,
        id: item._id
      }
      setStar(params).then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          // e
          // 更新本地存储用户的信息
          // this.$store.commit('LOGOUT')
          this.$store.commit('setUser', this.user)
          this.$store.commit('setToken', this.user)
        }
      })
    },
    // 点击返回
    onClickLeft () {
      this.$router.go(-1)
    },
    // 点击图片 显示遮罩层
    openImg (data) {
      this.overlayShow = true
      this.overlaySrc = data
    },
    // 时间戳转为时间
    timestampToTime (timestamp) {
      var date = new Date(timestamp) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '年'
      var M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '月'
      var D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日 '
      var h =
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      var m =
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
        ':'
      var s =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    },
    // UTC时间格式转通用格式时间
    // eslint-disable-next-line camelcase
    utc2beijing (utc_datetime) {
      // 转为正常的时间格式 年-月-日 时:分:秒
      // eslint-disable-next-line camelcase
      var T_pos = utc_datetime.indexOf('T')
      // eslint-disable-next-line camelcase
      var Z_pos = utc_datetime.indexOf('Z')
      // eslint-disable-next-line camelcase
      var year_month_day = utc_datetime.substr(0, T_pos)
      // eslint-disable-next-line camelcase
      var hour_minute_second = utc_datetime.substr(
        // eslint-disable-next-line camelcase
        T_pos + 1,
        // eslint-disable-next-line camelcase
        Z_pos - T_pos - 1
      )
      // eslint-disable-next-line camelcase
      var new_datetime = year_month_day + ' ' + hour_minute_second // 2017-03-31 08:02:06

      // 处理成为时间戳
      // eslint-disable-next-line no-use-before-define
      timestamp = new Date(Date.parse(new_datetime))
      // eslint-disable-next-line no-use-before-define
      timestamp = timestamp.getTime()
      // eslint-disable-next-line no-use-before-define
      timestamp = timestamp / 1000

      // 增加8个小时，北京时间比utc时间多八个时区
      // eslint-disable-next-line no-use-before-define
      var timestamp = timestamp + 8 * 60 * 60

      // 时间戳转为时间
      // eslint-disable-next-line camelcase
      var beijing_datetime = this.timestampToTime(timestamp * 1000)
      // eslint-disable-next-line camelcase
      return beijing_datetime // 2017-03-31 16:02:06
    },
    // 点击发送评论
    sendMessage () {
      if (!this.commentList.content) {
        Toast.fail('评论内容不能为空！')
        return
      }
      this.commentList.createTime = new Date()
      this.commentList.likeList = []
      this.commentList.user.push(this.user[0])
      let params = {
        commentList: this.commentList,
        id: this.postID
      }
      createCommentList(params).then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          // this.postList.commentList.push(this.commentList);
          this.getPostDetail()
          this.commentList.content = ''
          this.overlayCommentShow = false
        }
      })
    },
    commentPublish () {
      this.overlayCommentShow = true
    },
    // 用户详情页
    toUserDetail () {
      this.$router.push({
        name: 'UserDetail',
        query: { id: this.postList.user[0]._id }
      })
    },
    // 评论用户详情页
    toUserDetail1 (item) {
      this.$router.push({
        name: 'UserDetail',
        query: { id: item.user[0]._id }
      })
    },
    onSelect (action) {
      if (action.text === '删除') {
        Dialog.confirm({
          title: '提示',
          message: '删除帖子后相关数据将无法找回，您确定删除该帖子吗？'
        })
          .then(() => {
            // on confirm
            let params = {
              id: this.postID
            }
            removePost(params).then((res) => {
              if (res.data.code) {
                // Toast.fail(res.data.msg)
              } else {
                Toast.success(res.data.msg)
                this.$router.replace({ path: '/index' })
              }
            })
          })
          .catch(() => {
            // on cancel
          })
      } else if (action.text === '举报' || action.text === '取消举报') {
        Dialog.confirm({
          title: '提示',
          message: '您确定' + action.text + '该帖子吗？'
        })
          .then(() => {
            if (action.text === '举报') {
              this.isAdd = true
            } else {
              this.isAdd = false
            }
            // on confirm
            let params = {
              id: this.postID,
              userID: this.user[0]._id,
              isAdd: this.isAdd
            }
            setReportList(params).then((res) => {
              if (res.data.code) {
                // Toast.fail(res.data.msg)
              } else {
                Toast.success(res.data.msg)
                this.init()
              }
            })
          })
          .catch(() => {
            // on cancel
          })
      }
    },
    // 点击评论的赞
    lick_commentChange (item, index) {
      console.log('111', item)
      let length = this.postList.commentList.length - index - 1
      // 判断当前用户是否点赞过，即是否在likeList中 在则从likeList删除，不在则push进去
      if (item.likeList.indexOf(this.user[0]._id) === -1) {
        this.isAdd_comment = true
      } else {
        this.isAdd_comment = false
      }
      // 将likeList写入数据库
      let params = {
        isAdd: this.isAdd_comment,
        userID: this.user[0]._id,
        id: this.postID,
        createTime: this.commentListTime[length].createTime
      }
      setCommentLikeList(params).then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          console.log(index, length)
          item.likeList = res.data.Info[0].commentList[length].likeList
        }
      })
    },
    // 切换排序
    commentSort (value2) {
      if (value2 === 2) {
        this.postList.commentList = this.postList.commentList.sort(function (
          a,
          b
        ) {
          return b.likeList - a.likeList
        })
      } else {
        this.postList.commentList = this.commentListTime.reverse()
      }
    },
    // 删除评论
    deleteComment (item, index) {
      Dialog.confirm({
        title: '提示',
        message: '删除评论后相关数据将无法找回，您确定删除该评论吗？'
      })
        .then(() => {
          // on confirm
          let length = this.postList.commentList.length - index - 1
          let param = {
            id: this.postID,
            createTime: this.oldCommentList[index].createTime,
            index: length
          }
          deletePostcomment(param).then((res) => {
            if (res.data.code) {
              Toast.fail(res.data.msg)
            } else {
              Toast.success(res.data.msg)
              this.getPostDetail()
            }
          })
        })
        .catch(() => {
        // on cancel
        })
    }
  }
}
</script>
<style>
.commentWrap .commentTop .van-dropdown-menu__bar {
  box-shadow: none;
  height: 24px;
}
.commentWrap .commentTop .van-dropdown-menu__title {
  font-size: 0.1rem;
}
</style>
<style scoped>
.van-sidebar-item--select::before {
  background-color: #1989fa;
}
.postFooter .van-icon-like::before {
  color: #ffb6c1;
}
.campusCircleWrap {
  height: 100vh;
  display: flex;
  justify-content: flex-start;
}
.van-sidebar {
  height: calc(100vh - 50px - 46px);
  overflow-y: auto;
}
.van-sidebar::-webkit-scrollbar {
  width: 0;
}
.content {
  background-color: #f7f8fa;
  overflow-y: auto;
  width: 100%;
  margin-top: 46px;
}
.postHeader {
  text-align: left;
  display: flex;
  align-items: center;
}
.postHeader_img {
  width: 0.25rem;
  height: 0.25rem;
  margin-right: 0.08rem;
}
.postHeader_img > img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.postHeader_name {
  font-weight: 700;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 0.14rem;
  display: block;
}
.postHeader_time {
  color: #9d9d9d;
}
.postWrap {
  background-color: #ffffff;
  border-radius: 0 0 5px 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  padding: 8px 16px;
  position: relative;
}
.commentWrap {
  padding: 0 16px;
  background-color: #ffffff;
  border-radius: 5px 5px 0 0;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-top: 16px;
}
.postImg {
  display: flex;
  flex-wrap: wrap;
}
.postImg .van-image {
  margin: 0.05rem;
}
.postImg img {
  margin: 0.05rem;
}
.postImg img {
  width: calc((100% - 50px) / 3);
}
.postWord {
  text-align: left;
  margin: 5px 0;
}
.postFooter {
  text-align: left;
  color: #9d9d9d;
  display: flex;
  justify-content: space-around;
}
.postFooter .van-icon {
  vertical-align: middle;
}
.postFooter > div {
  display: flex;
  align-items: center;
}
.postFooter > div > span {
  margin-left: 3px;
}
.more {
  height: 60px;
  line-height: 60px;
  background: #f7f8fa;
}
.addModel {
  width: 2.5rem;
}
.addModel_title {
  margin-top: 15px;
  font-weight: 700;
  font-size: 0.13rem;
}
.postWord_span {
  font-weight: 700;
  font-size: 0.12rem;
}
.overlayimg {
  width: 100%;
  margin-top: calc(100vh - (100vh / 1.25));
}
.van-icon-star::before {
  color: yellow;
}
.sendMessage_Wrap {
  width: 100%;
  position: relative;
}
.sendMessage_input {
  width: 100%;
  height: 150px;
}
.sendMessage_button1 {
  position: absolute;
  bottom: 10px;
  right: 10px;
  height: 30px;
}
.sendMessage_button2 {
  position: absolute;
  bottom: 10px;
  right: 80px;
  height: 30px;
}
.comment_comtent {
  text-align: left;
  padding: 5px 0;
}
.floor {
  text-align: right;
  color: #9d9d9d;
}
.huanhang {
  white-space: pre-line;
}
.commentTop {
  display: flex;
  justify-content: space-between;
}
.comment_publish {
  padding: 5px 0;
  color: #1989fa;
}
.popover_more {
  position: absolute;
  right: 15px;
  top: 15px;
}
.commentListWrap {
  position: relative;
}
.comment_good {
  position: absolute;
  right: 0px;
  top: 0px;
  color: #9d9d9d;
}
.van-icon-good-job::before {
  color: #ffb6c1ed;
}
/* .popover_more2{
  position: absolute;
  top: 0;
  right: 0;
} */
</style>
